import React, { Component } from 'react';
import _ from 'lodash';
import { Text, View, PickerIOS } from 'react-native';
import styles from '../styles';
import { parseErrors, formStore } from '../..'
import StatusIcon from "../../statusIcon";
import SelectValue from '../selectValue';

const PickerItem = PickerIOS.Item;

export default class Selecter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: props.initialValue || '',
    };
  }
  componentWillReceiveProps(next) {
    if ((next.value !== this.props.value)) {
      this.setState({
        value: next.value
      }, () => {
        if (_.isFunction(this.props.afterChange)) {
          this.props.afterChange(next.value)
        }
      })
    }
  }
  options = (opts) => {
    const _opts = _.cloneDeep(opts);
    _opts.unshift({ label: '请选择', value: '' })
    return _.map(_opts, ({ label, value, fieldKey }, i) => {
      return <PickerItem key={`${fieldKey}_${value}_${i}`} label={label} value={value} />
    })
  }
  getLabel = (opts, value) => {
    const target = _.find(opts, ['value', value]);
    if (target) {
      return target.label;
    }
    return '';
  }
  activePicker = () => {
    formStore.activePickerIOS({
      key: this.props.fieldKey,
      options: this.props.options,
      value: this.props.initialValue,
      afterChange: this.props.afterChange
    })
  }
  render() {
    return (
      <View style={styles.wrap}>
        <View style={styles.label}>
          <Text style={this.props.error && styles.errorLabel}>{this.props.label}</Text>
        </View>
        <View style={[styles.value]}>
          <SelectValue
            onPress={this.activePicker}
            value={this.state.value}
            placeholder={this.props.placeholder}
            fn={this.getLabel.bind(null, this.props.options)}
          />
        </View>
        {this.props.error ? <StatusIcon type="error" msg={parseErrors(this.props.error)} /> : null}
      </View>
    )
  }
}